package com.huan.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "UserLoginFilter", urlPatterns = {"/pages/admin/*", "/servlet/*"})
public class UserLoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException
    {
        System.out.println("init==================");
    }

    public void destroy()
    {
        System.out.println("destroy==================");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException
    {
        System.out.println(this.getClass().getName() + "----------------------");
        String loginUser = null;
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();
        Object usernameObj = session.getAttribute("user");
        loginUser = (String) usernameObj;
        if (loginUser != null && !"".equals(loginUser)) {
            //if 登录成功放行
            chain.doFilter(request, response);
        } else {
            //else 未登录，跳转到 forward to index0.jsp
            HttpServletResponse resp = (HttpServletResponse) response;
            req.getRequestDispatcher("/index0.jsp").forward(req, resp);
        }
    }
}
